<?php
class dbbackups{
	
	public  $_filename="";
	public  $_savepath="";
	public $_savedir = "";
	
	function __construct(){
		 $this->CI = &get_instance();
		 $this->_savedir = "/data_sql_save/";
		 $this->_savepath= dirname(BASEPATH).$this->_savedir;
	}
	
	public function backup()
	{
		$insert = "";
		$this->_filename = "sql".time().".sql";
		
		$sql = 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"'.";\n";
		$sql .= 'SET time_zone="+00:00"'.";\n";
		
		$tables = $this->CI->db->list_tables();
		foreach($tables as $table){
			$insert .=  $this->tabletosql($table);
		    $insert .= $this->datatosql($table);
		}
		
		$sql .=$insert."\n\n";
		
		if(!file_put_contents($this->_savepath.$this->_filename,$sql)){
			return false;
		}
		return $this->_filename;
	}
	
	public function listtable()
	{
		$tables = $this->CI->db->list_tables();
		
		foreach($tables as $table){
			echo $table."<br>";
		}
	}
	
	public function savetolocal()
	{
		$sqldump = file_get_contents($this->_savepath.$this->_filename);
		
		ob_end_clean();
		header('Content-Encoding:none');
		header('Content-Type: '.(strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')?'application/octetstream' : 'application/octet-stream'));
		header('Content-Disposition: '.(strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')?'inline;':'attachment; ').'filename="'.$this->_filename);
		header('Content-Length: '.strlen($sqldump));
		header('Pragma: no-cache');
		header('Expires: 0');
		echo $sqldump;
	}
	
	/*     哈哈哈，以下 tabletosql 和datatosql两个方法参考了51cto上的写法，而那个作者又是参照了DISCUZ的呵呵，
	 * 
	 *      tabletosql 参数为一个表的名字，返回创建这个表的SQL语句。
	 */
	
	public function tabletosql($tableName)
	{
		$res = $this->CI->db->query("show create table $tableName")->result_array();
		
		$create = array();
		foreach($res[0] as $r)
		{
			$create[] = $r;
		}
		$create[1].=";\n";
		return $create[1];
	}
	
	/*
	 *   datatosql 参数为一个表的名字，返回这个表的把有数据，生成INSERT SQL语句。
	 * 
	 */
	public function datatosql($tableName)
	{
		$rows = $this->CI->db->query("select * from $tableName")->result_array();
		
		$fields = $this->CI->db->list_fields($tableName);
		//print_r($fields);
		$insert = "";
		foreach($rows as $row)
		{
            $insert .= "insert into "."`".$tableName."`". "(";
            foreach($fields as $field){
            	$insert .= $field.",";
            }
            $insert = substr($insert,0,strlen($insert)-1);
            $insert .= ") values(";
            
            $count = count($row);
            
            for($i=0;$i<$count; $i++){
            
            	if(is_int($fields[$i])){
            	    $insert .= $row[$fields[$i]];
            	}else{	
            	    $insert .= "'".mysql_escape_string($row[$fields[$i]])."',";
            	}
            }
            $insert = substr($insert,0,strlen($insert)-1);
            $insert .= ");\n";
			
		}
		
		return $insert;
		
	}
	
}